<template>
  <view class="records-page">
    <!-- 订单进度卡片 -->
    <view class="progress-card">
      <view class="progress-header">
        <text class="progress-title">服务进度</text>
        <view class="status-badge" :class="statusClass">
          {{ getStatusText(progress.orderStatus) || '待开始' }}
        </view>
      </view>
      
      <!-- 进度条 -->
      <view class="progress-bar-container">
        <view class="progress-steps">
          <view class="step" :class="{ active: hasStarted, completed: hasStarted }">
            <view class="step-icon">🚀</view>
            <text class="step-text">开始</text>
          </view>
          <view class="step-line" :class="{ completed: isInProgress || isCompleted }"></view>
          <view class="step" :class="{ active: isInProgress || isCompleted, completed: isCompleted }">
            <view class="step-icon">📸</view>
            <text class="step-text">进行中</text>
          </view>
          <view class="step-line" :class="{ completed: isCompleted }"></view>
          <view class="step" :class="{ active: isCompleted, completed: isCompleted }">
            <view class="step-icon">✅</view>
            <text class="step-text">完成</text>
          </view>
        </view>
      </view>
      
      <view class="progress-info">
        <view class="info-item">
          <text class="info-label">陪爬员</text>
          <text class="info-value">{{ progress.climberName || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">开始时间</text>
          <text class="info-value">{{ formatTime(progress.startTime) || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">照片数量</text>
          <text class="info-value">{{ progress.photoCount || 0 }} 张</text>
        </view>
      </view>
    </view>

    <!-- 服务记录时间轴 -->
    <view class="timeline-container">
      <view class="timeline-title">服务记录</view>
      
      <view v-if="records.length === 0" class="empty-state">
        <text class="empty-icon">📝</text>
        <text class="empty-text">暂无服务记录</text>
      </view>
      
      <view v-else class="timeline">
        <view 
          v-for="(record, index) in records" 
          :key="record.id"
          class="timeline-item">
          <!-- 时间轴节点 -->
          <view class="timeline-node">
            <view class="node-dot" :class="['node-' + (record.recordType || '').toLowerCase()]"></view>
            <view v-if="index < records.length - 1" class="node-line"></view>
          </view>
          
          <!-- 记录内容 -->
          <view class="timeline-content">
            <view class="record-header">
              <text class="record-type">{{ getRecordTypeText(record.recordType) }}</text>
              <text class="record-time">{{ formatTime(record.createTime) }}</text>
            </view>
            
            <view class="record-desc" v-if="record.description">
              {{ record.description }}
            </view>
            
            <!-- 照片网格 -->
            <view v-if="record.imageList && record.imageList.length > 0" class="photo-grid">
              <image
                v-for="(img, imgIndex) in record.imageList"
                :key="imgIndex"
                :src="getImageUrl(img)"
                mode="aspectFill"
                class="photo-item"
                @click="previewImage(record.imageList, imgIndex)"
              />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- SOS紧急求助悬浮按钮 (仅在服务进行中显示) -->
    <emergency-sos v-if="isInProgress" :bottom="220" :right="30"></emergency-sos>

    <!-- 底部操作栏 -->
    <bottom-action-bar 
      :show-call-button="progress.climberName && progress.climberName !== '待分配'"
      :show-location-button="isInProgress"
      :climber-phone="climberPhone"
      @refresh="loadData"
      @sendMessage="handleSendMessage"
      @viewLocation="handleViewLocation">
    </bottom-action-bar>
  </view>
</template>

<script>
import { getOrderProgress, getServiceRecords } from '@/api/service'
import config from '@/config'
import EmergencySos from '@/components/emergency-sos/emergency-sos.vue'
import BottomActionBar from '@/components/bottom-action-bar/bottom-action-bar.vue'

export default {
  components: {
    EmergencySos,
    BottomActionBar
  },
  
  data() {
    return {
      orderId: '',
      progress: {
        orderStatus: '',
        climberName: '加载中...',
        startTime: null,
        photoCount: 0
      },
      records: [],
      loading: true,
      error: null,
      climberPhone: '' // 陪爬员电话
    }
  },
  
  computed: {
    // 是否已开始
    hasStarted() {
      return ['IN_PROGRESS', 'COMPLETED'].includes(this.progress.orderStatus)
    },
    // 是否进行中
    isInProgress() {
      return this.progress.orderStatus === 'IN_PROGRESS'
    },
    // 是否已完成
    isCompleted() {
      return this.progress.orderStatus === 'COMPLETED'
    },
    // 状态样式类
    statusClass() {
      const classMap = {
        'PENDING': 'status-pending',
        'CONFIRMED': 'status-confirmed',
        'IN_PROGRESS': 'status-progress',
        'COMPLETED': 'status-completed',
        'CANCELLED': 'status-cancelled'
      }
      return classMap[this.progress.orderStatus] || ''
    }
  },
  
  onLoad(options) {
    if (!options.orderId) {
      uni.showToast({ title: '订单ID缺失', icon: 'none' })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    this.orderId = options.orderId
    this.loadData()
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      this.error = null
      
      try {
        await Promise.all([
          this.loadProgress(),
          this.loadRecords()
        ])
      } catch (error) {
        this.error = error.message || '加载失败'
      } finally {
        this.loading = false
      }
    },
    
    // 加载进度
    async loadProgress() {
      try {
        console.log('========== 开始加载订单进度 ==========')
        console.log('订单ID:', this.orderId)
        
        const res = await getOrderProgress(this.orderId)
        console.log('API响应完整数据:', JSON.stringify(res, null, 2))
        
        // 处理不同的响应格式
        let progressData = null
        if (res.code === 200 && res.data) {
          progressData = res.data
        } else if (res.data) {
          progressData = res.data
        } else if (res.code === 200) {
          progressData = res
        }
        
        console.log('解析后的进度数据:', progressData)
        
        if (progressData) {
          this.progress = {
            orderStatus: progressData.orderStatus || 'PENDING',
            climberName: progressData.climberName || '待分配',
            startTime: progressData.startTime || null,
            photoCount: progressData.photoCount || 0
          }
          console.log('最终设置的progress:', this.progress)
        } else {
          console.error('未能解析到有效数据')
          throw new Error('数据格式错误')
        }
        
        console.log('========== 订单进度加载完成 ==========')
      } catch (error) {
        console.error('❌ 加载进度失败:', error)
        this.error = error.message || '加载进度失败'
        uni.showToast({ title: '加载进度失败: ' + (error.message || '未知错误'), icon: 'none' })
        throw error
      }
    },
    
    // 加载服务记录
    async loadRecords() {
      try {
        console.log('========== 开始加载服务记录 ==========')
        console.log('订单ID:', this.orderId)
        
        const res = await getServiceRecords(this.orderId)
        console.log('API响应完整数据:', JSON.stringify(res, null, 2))
        
        // 处理不同的响应格式
        let recordsData = null
        if (res.code === 200 && res.data) {
          recordsData = res.data
        } else if (Array.isArray(res.data)) {
          recordsData = res.data
        } else if (Array.isArray(res)) {
          recordsData = res
        }
        
        console.log('解析后的记录数组:', recordsData)
        
        if (recordsData) {
          this.records = recordsData
          console.log('最终设置的records:', this.records)
        } else {
          this.records = []
          console.log('未找到服务记录，设置为空数组')
        }
        
        console.log('========== 服务记录加载完成 ==========')
      } catch (error) {
        console.error('❌ 加载记录失败:', error)
        this.error = error.message || '加载服务记录失败'
        uni.showToast({ title: '加载失败: ' + (error.message || '未知错误'), icon: 'none' })
        throw error
      }
    },
    
    // 获取图片URL
    getImageUrl(path) {
      if (!path) return ''
      // 如果是完整URL直接返回
      if (path.startsWith('http')) {
        return path
      }
      // 否则拼接服务器地址
      return config.baseUrl + path
    },
    
    // 预览图片
    previewImage(imageList, current) {
      const urls = imageList.map(img => this.getImageUrl(img))
      uni.previewImage({
        urls: urls,
        current: current
      })
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '-'
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      
      // 1分钟内
      if (diff < 60000) {
        return '刚刚'
      }
      // 1小时内
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      }
      // 今天
      if (date.toDateString() === now.toDateString()) {
        return date.getHours() + ':' + String(date.getMinutes()).padStart(2, '0')
      }
      // 其他
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待接单',
        'CONFIRMED': '已确认',
        'IN_PROGRESS': '进行中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    },
    
    // 获取记录类型文本
    getRecordTypeText(type) {
      const typeMap = {
        'START': '🚀 开始服务',
        'PHOTO': '📸 服务记录',
        'END': '✅ 服务完成'
      }
      return typeMap[type] || type
    },
    
    // ==================== 底部操作栏事件处理 ====================
    
    // 发送消息给陪爬员
    handleSendMessage() {
      console.log('发送消息给陪爬员')
      // TODO: 实现聊天功能
    },
    
    // 查看陪爬员位置
    handleViewLocation() {
      console.log('查看陪爬员位置')
      // TODO: 实现地图位置查看功能
      // uni.navigateTo({
      //   url: `/pages/map/location?orderId=${this.orderId}`
      // })
    }
  }
}
</script>

<style scoped>
.records-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20rpx;
}

/* 进度卡片 */
.progress-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  color: #fff;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.progress-title {
  font-size: 36rpx;
  font-weight: bold;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  background: rgba(255, 255, 255, 0.3);
}

.progress-info {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12rpx;
  padding: 20rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
}

.info-label {
  font-size: 28rpx;
  opacity: 0.8;
}

.info-value {
  font-size: 28rpx;
  font-weight: 500;
}

/* 进度条 */
.progress-bar-container {
  margin: 30rpx 0;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 12rpx;
}

.progress-steps {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 0 0 auto;
  opacity: 0.5;
  transition: all 0.3s;
}

.step.active {
  opacity: 1;
}

.step.completed {
  opacity: 1;
}

.step-icon {
  width: 60rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  margin-bottom: 8rpx;
  transition: all 0.3s;
}

.step.active .step-icon,
.step.completed .step-icon {
  background: rgba(255, 255, 255, 0.9);
  transform: scale(1.1);
}

.step-text {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.8);
}

.step.active .step-text,
.step.completed .step-text {
  color: #fff;
  font-weight: 600;
}

.step-line {
  flex: 1;
  height: 4rpx;
  background: rgba(255, 255, 255, 0.3);
  margin: 0 10rpx 40rpx;
  transition: all 0.3s;
}

.step-line.completed {
  background: rgba(255, 255, 255, 0.9);
}

/* 时间轴容器 */
.timeline-container {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
}

.timeline-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
}

.empty-icon {
  font-size: 100rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #909399;
}

/* 时间轴 */
.timeline {
  position: relative;
}

.timeline-item {
  display: flex;
  margin-bottom: 40rpx;
}

.timeline-item:last-child {
  margin-bottom: 0;
}

/* 时间轴节点 */
.timeline-node {
  width: 60rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20rpx;
}

.node-dot {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  flex-shrink: 0;
}

.node-start {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.node-photo {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.node-end {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.node-line {
  width: 4rpx;
  flex: 1;
  background: #e4e7ed;
  margin-top: 10rpx;
}

/* 时间轴内容 */
.timeline-content {
  flex: 1;
  padding-bottom: 20rpx;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.record-type {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.record-time {
  font-size: 24rpx;
  color: #909399;
}

.record-desc {
  font-size: 28rpx;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 15rpx;
}

/* 照片网格 */
.photo-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15rpx;
}

.photo-item {
  width: 100%;
  height: 200rpx;
  border-radius: 8rpx;
  object-fit: cover;
}
</style>

